﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;
using System.IO;
using DSkin.Forms;
using System.Runtime.InteropServices;

namespace SocketProject
{

    public partial class FrmServer : Skin_VS_Dark
    {
        public FrmServer()
        {
            InitializeComponent();
            DS.ScrollBarStyle.SetScrollBarStyle(dSkinListBoxTask);
            DS.ScrollBarStyle.SetScrollBarStyle(dSkinListBoxCalc);
            DS.ScrollBarStyle.SetScrollBarStyle(dSkinListBoxComplete);
            DS.ScrollBarStyle.SetScrollBarStyle(dSkinListBoxClient);
        }

        SC.SocketServer socketServer;

        private void FrmServer_Load(object sender, EventArgs e)
        {
            try
            {
                socketServer = new SC.SocketServer();
            }
            catch (Exception ex)
            {
                Common.Log.Warn(ex.Message, ex);
            }
            socketServer.clientConnectedEvent = AddHostItem;
            socketServer.recvEvent = Receive;

            socketServer.checkBeatEvent = CheckBeatEvent;

            Invoke(new MethodInvoker(() => {
                this.txt_IP.Text = socketServer.serverProfile.serverIp;
                this.txt_Port.Text = socketServer.serverProfile.serverPort.ToString();
            }));

            
            Thread sendTaskThread = new Thread(new ParameterizedThreadStart(BeginTaskList));
            sendTaskThread.IsBackground = true;
            sendTaskThread.Start(tasklist2);
            bContinue = true;
        }

        /// <summary>
        /// 待分配任务列表字典
        /// </summary>
        Dictionary<string, DS.Controls.DSFolderListItem> taskListItemDic = new Dictionary<string, DS.Controls.DSFolderListItem>();
        /// <summary>
        /// 计算中列表字典
        /// </summary>
        Dictionary<string, DS.Controls.DSFolderListItem> calcListItemDic = new Dictionary<string, DS.Controls.DSFolderListItem>();
        /// <summary>
        /// 已完成列表字典
        /// </summary>
        Dictionary<string, DS.Controls.DSFolderListItem> completeListItemDic = new Dictionary<string, DS.Controls.DSFolderListItem>();
        /// <summary>
        /// 客户端列表字典
        /// </summary>
        Dictionary<string, DS.Controls.DSClientListItem> clientListItemDic = new Dictionary<string, DS.Controls.DSClientListItem>();

        /// <summary>
        /// 待分配任务列表
        /// </summary>
        List<string> tasklist = new List<string>();

        List<Common.TaskItemData> tasklist2 = new List<Common.TaskItemData>();


        private List<string> tasklistdata = new List<string>();
        /// <summary>
        /// 控制停止标志
        /// </summary>
        bool bContinue;

        private void ReceiveMsg(string strMsg)
        {
            this.txt_Log.AppendText(strMsg + " \r \n");
        }

        /// <summary>
        /// 处理接收到的消息数据包
        /// </summary>
        /// <param name="objBuf"></param>
        private void Receive(Socket socketSend,SC.MessageType messageType, byte[] objBuf)
        {
            //SC.MessagePack messagePack = SC.MessagePack.DeserializeObject(data); //解析消息类型
            switch (messageType)
            {
                case SC.MessageType.ClientConnect:
                    List<Common.TaskItemData> taskListRecv = SC.MessagePack.DeserializeObject<List<Common.TaskItemData>>(objBuf);

                    foreach (Common.TaskItemData taskItemData in taskListRecv)
                    {
                        //Common.TaskItemData taskItemData = new Common.TaskItemData(importpath,"",Common.TaskItemState.idle);
                        taskItemData.ipEndPoint = socketSend.RemoteEndPoint.ToString();
                        DS.Controls.DSFolderListItem item = new DS.Controls.DSFolderListItem(taskItemData);
                        AddCalcItem(item);
                    }
                    //更新任务数
                    string key = socketSend.RemoteEndPoint.ToString();
                    clientListItemDic[key].clientItemData.taskCount = taskListRecv.Count;
                    clientListItemDic[socketSend.RemoteEndPoint.ToString()].duiTaskCount.Text = clientListItemDic[key].clientItemData.taskCount.ToString();

                    break;
                case SC.MessageType.BeginTask:
                    string importItemPath1 = SC.MessagePack.DeserializeObject<string>(objBuf);
                    string key1 = Common.MD5Hash.GetstrMD5(importItemPath1); 
                    Invoke(new MethodInvoker(() => {
                        if (calcListItemDic.ContainsKey(key1))
                        {
                            calcListItemDic[key1].SetState(Common.TaskItemState.busy);
                        }
                        clientListItemDic[socketSend.RemoteEndPoint.ToString()].State = Common.ClientItemState.busy;
                        //clientListItemDic[clientKey].State = Common.ItemState.working;
                        Common.Log.Info("开始计算" + importItemPath1);
                    }));
                    break;
                case SC.MessageType.EndTask:
                    string importItemPath2 = SC.MessagePack.DeserializeObject<string>(objBuf);
                    string key2 = Common.MD5Hash.GetstrMD5(importItemPath2);
                    if (calcListItemDic.ContainsKey(key2))
                    {
                        Invoke(new MethodInvoker(() => {

                            dSkinListBoxTask.Items.Remove(calcListItemDic[key2]);

                            if (!completeListItemDic.ContainsKey(key2))
                            {
                                calcListItemDic[key2].SetState(Common.TaskItemState.complete);
                                completeListItemDic.Add(key2, calcListItemDic[key2]);
                                dSkinListBoxComplete.Items.Add(calcListItemDic[key2]);
                            }
                            calcListItemDic.Remove(key2);
                            Common.Log.Info(importItemPath2 + "计算完成");
                        }));
                    }
                    break;
                case SC.MessageType.HertBeat:
                    //string ipkey = SC.MessagePack.DeserializeObject<string>(objBuf);
                    BeatHeart(socketSend.RemoteEndPoint.ToString());
                    break;
                case SC.MessageType.CloseClient:
                    //string clientkey = SC.MessagePack.DeserializeObject<string>(objBuf);
                    string clientkey = socketSend.RemoteEndPoint.ToString();
                    socketServer.CloseClient(clientkey);
                    RemoveClientItem(clientkey);
                    break;
                case SC.MessageType.StateChange:
                    Common.ClientItemData clientItemData = SC.MessagePack.DeserializeObject<Common.ClientItemData>(objBuf);
                    clientItemData.ipEndPoint = socketSend.RemoteEndPoint.ToString();//节点的ipEndPoint统一为 服务端获取的RemoteEndPoint
                    string ipkey = clientItemData.ipEndPoint;
                    BeginInvoke(new MethodInvoker(() => {
                        if (clientListItemDic.ContainsKey(ipkey))
                        {
                            if (clientItemData.taskCount == 0)
                            {
                                clientListItemDic[ipkey].State = clientItemData.clientItemState;
                            }

                            clientListItemDic[ipkey].clientItemData = clientItemData;
                            clientListItemDic[ipkey].duiTaskCount.Text = clientItemData.taskCount.ToString();
                        }
                    }));
                    break;
                case SC.MessageType.RecvTaskSucceed:
                    //Common.TaskItemData itemData = SC.MessagePack.DeserializeObject<Common.TaskItemData>(objBuf);
                    //itemData.ipEndPoint = socketSend.RemoteEndPoint.ToString();//节点的ipEndPoint统一为 服务端获取的RemoteEndPoint
                    ////if (calcListItemDic.ContainsKey(itemData.md5key))
                    ////{
                    ////    calcListItemDic[itemData.md5key].TaskitemData = itemData;
                    ////}
                    //Common.Log.Debug(itemData.importpath);
                    break;
            }
        }

        /// <summary>
        /// 接收到心跳改变该主机状态
        /// </summary>
        /// <param name="ipkey"></param>
        private void BeatHeart(string ipkey)
        {
            if (socketServer.heartBeatDic.ContainsKey(ipkey))
            {
                socketServer.heartBeatDic[ipkey] = true;
            }
            else
            {
                socketServer.heartBeatDic.Add(ipkey, true);
            }
        }

        /// <summary>
        /// 删除一个客户端
        /// </summary>
        /// <param name="clientkey"></param>
        private void RemoveClientItem(string clientkey)
        {
            Invoke(new MethodInvoker(() => {
                if (clientListItemDic.ContainsKey(clientkey))
                {
                    ///删除 列表客户端
                    dSkinListBoxClient.Items.Remove(clientListItemDic[clientkey]);
                    clientListItemDic.Remove(clientkey);
                    socketServer.heartBeatDic.Remove(clientkey);
                    Common.Log.Warn("移除客户端"+clientkey);
                    ReDistributeTask(clientkey);
                }
            }));
        }

        /// <summary>
        /// 重新分配已断开主机的任务
        /// </summary>
        /// <param name="clientkey"></param>
        private void ReDistributeTask(string clientkey)
        {
            Common.Log.Warn("检测到客户端" + clientkey + "断开连接,重新分发任务");
            List<Common.TaskItemData> taskItemDatas = new List<Common.TaskItemData>();//暂存calcListItemDic数据
            foreach (string key in calcListItemDic.Keys)
            {
                taskItemDatas.Add(calcListItemDic[key].TaskitemData);
            }

            foreach (Common.TaskItemData taskItemData in taskItemDatas)//如果有任务分配给该ip 重新分配给其它主机
            {
                string ip = taskItemData.ipEndPoint;
                
                if (clientkey.Equals(ip))
                {
                    DeleteTaskItem(calcListItemDic[taskItemData.md5key]);
                    AddTaskItem(taskItemData);
                }
            }
        }

        /// <summary>
        /// 检查心跳状态 移除没心跳的节点
        /// </summary>
        private void CheckBeatEvent()
        {
            List<String> deadKey = new List<String>();
            foreach (var item in socketServer.heartBeatDic)
            {
                if (item.Value == false)
                {
                    deadKey.Add(item.Key);
                }
            }
            foreach (String key in deadKey)
            {
                RemoveClientItem(key);
                Common.Log.Warn(key+"检测客户端到没有心跳执行移除操作");
            }

            if (dSkinListBoxClient.Items.Count > 0)
            {
                DS.Controls.DSClientListItem busyItem = GetBusyItem(dSkinListBoxClient);
                if (busyItem.clientItemData.taskCount > GetIdelItem(dSkinListBoxClient).clientItemData.taskCount + 1)
                {
                    DS.Controls.DSFolderListItem lastBusyTask = null;
                    foreach (DS.Controls.DSFolderListItem busyTask in dSkinListBoxCalc.Items)
                    {
                        if (busyTask.ItemData.ipEndPoint!=null 
                            && busyTask.ItemData.ipEndPoint.Equals(busyItem.clientItemData.ipEndPoint) 
                            && busyTask.ItemData.taskItemState==Common.TaskItemState.idle)
                        {
                            lastBusyTask = busyTask;
                            break;
                        }
                    }

                    Common.Log.Info("动态调控任务");
                    //最忙主机分配一个任务给空闲主机
                    DeleteTaskItem(lastBusyTask);
                    AddTaskItem(lastBusyTask.TaskitemData);
                    
                }
            }
        }

        /// <summary>
        /// 响应客户端接入事件
        /// </summary>
        /// <param name="strIP"></param>
        private void AddHostItem(string strIP)
        {
            //this.cmb_Socket.Items.Add(strItem);
            Common.ClientItemData clientItemData = new Common.ClientItemData(strIP,Common.ClientItemState.idle,0);
            DS.Controls.DSClientListItem dsHostListItem =  new DS.Controls.DSClientListItem(clientItemData);
            //dsHostListItem.Ip = strIP;
            //dsHostListItem.State = Common.ClientItemState.idle;
            this.dSkinListBoxClient.Items.Add(dsHostListItem);
            clientListItemDic.Add(dsHostListItem.Ip,dsHostListItem);

            BeatHeart(dsHostListItem.clientItemData.ipEndPoint);

            Common.Log.Info(strIP + "接入成功");
            
        }

        /// <summary>
        /// 服务器给客户端发送消息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Start_Click(object sender, EventArgs e)
        {
            StartNewTask();
            //socketSend.Send(buffer);
        }

        private void StartNewTask()
        {
            try
            {

                foreach (DS.Controls.DSFolderListItem node in dSkinListBoxTask.Items)
                {
                    tasklist2.Add(new Common.TaskItemData( node.Path,"",Common.TaskItemState.idle));
                }

            }
            catch (Exception ex)
            {
                Common.Log.Warn(ex.Message, ex);
            }
        }


        /// <summary>
        /// 后台常住线程 分发任务
        /// </summary>
        /// <param name="obj"></param>
        private void BeginTaskList(object obj)
        {
            Common.Log.Info("分发线程启动成功");
            //List<string> tasklist = obj as List<string>; 
            while(true)
            {
                System.Threading.Thread.Sleep(100);

                if (tasklist2 != null && tasklist2.Count > 0 && bContinue)
                {
                    if (this.dSkinListBoxClient.Items.Count > 0 && dSkinListBoxTask.Items.Count > 0)
                    {
                        DS.Controls.DSClientListItem idelItem = GetIdelItem(dSkinListBoxClient);
                        DS.Controls.DSFolderListItem node = dSkinListBoxTask.Items[0] as DS.Controls.DSFolderListItem;
                        if (idelItem.clientItemData.taskCount < socketServer.serverProfile.maxTaskCount)//限制最大分配任务数量
                        {
                            idelItem.clientItemData.taskCount = idelItem.clientItemData.taskCount + 1;//先将分配任务数量+1 稍后根据客户端数据同步 防止网络延迟导致数据不同步

                            //List<string> OneItemList = new List<string>();
                            //OneItemList.Add(tasklist[0]);

                            List<Common.TaskItemData> OneItemList2 = new List<Common.TaskItemData>();
                            OneItemList2.Add(tasklist2[0]);

                            byte[] taskObj = SC.MessagePack.SerializeObject(SC.MessageType.RenderTask, OneItemList2);
                            try 
                            {
                                Common.Log.Info("分发任务 "+ OneItemList2[0]+ " 给 " + idelItem.Ip);
                                node.ItemData.ipEndPoint = idelItem.Ip;
                                socketServer.dicSocket[idelItem.Ip].Send(taskObj);
                                Common.Log.Warn("发送任务成功");
                            }
                            catch(Exception ex)
                            {
                                Common.Log.Warn("发送任务失败", ex);
                            }
                            
                            lock (tasklist2)
                            {

                                    tasklist2.RemoveAt(0);

                            }

                            if (dSkinListBoxTask.Items.Count > 0)
                            {
                                //DS.Controls.DSFolderListItem node = dSkinListBoxTask.Items[0] as DS.Controls.DSFolderListItem;
                                AddCalcItem(node);
                            }
                        }

                    }
                }
                else
                {
                    System.Threading.Thread.Sleep(100);
                }

            }
        }

        /// <summary>
        /// Add CalcItems
        /// </summary>
        /// <param name="node"></param>
        private void AddCalcItem(DS.Controls.DSFolderListItem node)
        {
            string key = node.ItemData.md5key;
            if (!calcListItemDic.ContainsKey(key))
            {
                Invoke(new MethodInvoker(() =>
                {
                    if (taskListItemDic.ContainsKey(key))
                    {
                        dSkinListBoxTask.Items.Remove(node);
                        taskListItemDic.Remove(key);
                    }
                    dSkinListBoxCalc.Items.Add(node);
                }));
                calcListItemDic.Add(key, node);
            }
        }

        /// <summary>
        /// 获取任务最少主机
        /// </summary>
        /// <returns></returns>
        private DS.Controls.DSClientListItem GetIdelItem(DSkin.Controls.DSkinListBox dSkinListBoxClient)
        {
            DS.Controls.DSClientListItem idelItem = null;
            if(dSkinListBoxClient.Items.Count>0)
            {
                idelItem = dSkinListBoxClient.Items[0] as DS.Controls.DSClientListItem;

                foreach (DS.Controls.DSClientListItem item in dSkinListBoxClient.Items)
                {
                    if (idelItem.clientItemData.taskCount > item.clientItemData.taskCount && item.clientItemData.ipEndPoint!=null)
                    {
                        idelItem = item;
                    }
                }
            }
            return idelItem;
        }


        /// <summary>
        /// 获取任务最多主机
        /// </summary>
        /// <returns></returns>
        private DS.Controls.DSClientListItem GetBusyItem(DSkin.Controls.DSkinListBox dSkinListBoxClient) 
        {
            DS.Controls.DSClientListItem busyItem = null;
            if (dSkinListBoxClient.Items.Count > 0)
            {
                busyItem = dSkinListBoxClient.Items[0] as DS.Controls.DSClientListItem;

                foreach (DS.Controls.DSClientListItem item in dSkinListBoxClient.Items)
                {
                    if (busyItem.clientItemData.taskCount < item.clientItemData.taskCount)
                    {
                        busyItem = item;
                    }
                }
            }

            return busyItem;
        }


        /// <summary>
        /// 停止监听
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_StopListen_Click(object sender, EventArgs e)
        {
            socketServer.Close();
        }


        /// <summary>
        /// 数据库操作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            SocketServer.DBHelper.InsertFinish("md50000000000", "sourcepath123", "destpath456");
            //string msg = "okffffffffffffffff";
            //byte[] myByte = System.Text.Encoding.UTF8.GetBytes(msg);
            bool b = SocketServer.DBHelper.IsExist("md50000000000");
        }


        private void FrmServer_DragDrop(object sender, DragEventArgs e)
        {
            try
            {
                string importpath = ((System.Array)e.Data.GetData(DataFormats.FileDrop)).GetValue(0).ToString();
                //AddTaskItem(importpath);
                Common.TaskItemData taskItemData = new Common.TaskItemData(importpath,"",Common.TaskItemState.idle);
                AddTaskItem(taskItemData);
            }
            catch(Exception ex)
            {
                Common.Log.Warn(ex.Message, ex);
            }
        }

        /// <summary>
        /// 新增任务 将item放入taslkist2 并且在界面显示
        /// </summary>
        /// <param name="importItemPath"></param>
        private void AddTaskItem(string importItemPath)
        {
            Common.TaskItemData itemData = new Common.TaskItemData(importItemPath, "abcdefg", Common.TaskItemState.idle);
            DS.Controls.DSFolderListItem item = new DS.Controls.DSFolderListItem(itemData);

            string key = Common.MD5Hash.GetstrMD5(importItemPath);

            if (!calcListItemDic.ContainsKey(key) && !completeListItemDic.ContainsKey(key) && !taskListItemDic.ContainsKey(key))
            {
                Invoke(new MethodInvoker(() => {
                    dSkinListBoxTask.Items.Add(item);
                }));
                
                taskListItemDic.Add(key,item);
                lock (tasklist2)
                {
                    tasklist2.Add(new Common.TaskItemData(item.ItemData.importpath,item.ItemData.exportpath,Common.TaskItemState.idle));
                }
                
            }
            else
            {
                Invoke(new MethodInvoker(() => {
                    string errlog = importItemPath + "已存在\r\n";
                    this.txt_Log.Text += errlog;
                    Common.Log.Warn(errlog);
                }));
            }
        }

        /// <summary>
        /// 新增任务 将item放入taslkist2 并且在界面显示
        /// </summary>
        /// <param name="importItemPath"></param>
        private void AddTaskItem(Common.TaskItemData itemData)
        {
            //Common.TaskItemData itemData = new Common.TaskItemData(importItemPath, "abcdefg", Common.TaskItemState.idle);
            DS.Controls.DSFolderListItem item = new DS.Controls.DSFolderListItem(itemData);

            string key = Common.MD5Hash.GetstrMD5(itemData.importpath);

            if (!calcListItemDic.ContainsKey(key) && !completeListItemDic.ContainsKey(key) && !taskListItemDic.ContainsKey(key))
            {
                Invoke(new MethodInvoker(() => {
                    dSkinListBoxTask.Items.Add(item);
                }));

                taskListItemDic.Add(key, item);
                lock (tasklist2)
                {
                    tasklist2.Add(itemData);
                }

            }
            else
            {
                Invoke(new MethodInvoker(() => {
                    string errlog = itemData.importpath + "已存在\r\n";
                    this.txt_Log.Text += errlog;
                    Common.Log.Warn(errlog);
                }));
            }
        }

        private void dSkinListBox2_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))//dragdrop 响应方式
            {
                e.Effect = DragDropEffects.Link;
            }
            else
            {
                e.Effect = DragDropEffects.None;
            }
        }

        /// <summary>
        /// 删除选中的ListBoxItem
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_deleteitem_Click(object sender, EventArgs e)
        {
            if (dSkinTabControl1.SelectedTab == dSkinTabPageTask)
            {
                foreach (DS.Controls.DSFolderListItem selecteditem in dSkinListBoxTask.SelectedItems)
                {
                    dSkinListBoxTask.Items.Remove(selecteditem);
                    string key = selecteditem.ItemData.md5key;

                    

                    if (taskListItemDic.ContainsKey(key))
                    {
                        taskListItemDic.Remove(key);

                        Common.TaskItemData item = tasklist2.FirstOrDefault(itemdata => itemdata.importpath == selecteditem.Path);
                        if (item != null)
                        {
                            tasklist2.Remove(item);
                        }

                        //if (tasklist2.Contains(selecteditem.Path))
                        //{
                        //    tasklist2.Remove(selecteditem.Path);
                        //}
                    }
                }
            }
            else if (dSkinTabControl1.SelectedTab == dSkinTabPageComplete)
            {
                foreach (DS.Controls.DSFolderListItem selecteditem in dSkinListBoxComplete.SelectedItems)
                {
                    dSkinListBoxComplete.Items.Remove(selecteditem);
                    string key = selecteditem.ItemData.md5key;
                    if (completeListItemDic.ContainsKey(key))
                    {
                        completeListItemDic.Remove(key);
                    }
                }
            }
            else if (dSkinTabControl1.SelectedTab == dSkinTabPageCalc)
            {
                foreach (DS.Controls.DSFolderListItem selecteditem in dSkinListBoxCalc.SelectedItems)
                {
                    DeleteTaskItem(selecteditem);
                }
            }
        }

        /// <summary>
        /// 删除已分配任务
        /// </summary>
        /// <param name="selecteditem"></param>
        private void DeleteTaskItem(DS.Controls.DSFolderListItem selecteditem)
        {
            if (selecteditem != null)
            {
                Invoke(new MethodInvoker(() => {
                    dSkinListBoxCalc.Items.Remove(selecteditem);
                }));
                string key = selecteditem.TaskitemData.md5key;
                if (calcListItemDic.ContainsKey(key))
                {
                    calcListItemDic.Remove(key);
                    //if (tasklist.Contains(selecteditem.Path))
                    //{
                    //    tasklist.Remove(selecteditem.Path);
                    //}

                    Common.TaskItemData item = tasklist2.FirstOrDefault(itemdata => itemdata.importpath == selecteditem.Path);
                    if (item != null)
                    {
                        tasklist2.Remove(item);
                    }

                    byte[] deleteObj = SC.MessagePack.SerializeObject(SC.MessageType.Delete, selecteditem.TaskitemData);
                    if (socketServer.dicSocket[selecteditem.TaskitemData.ipEndPoint].Connected)
                    {
                        socketServer.dicSocket[selecteditem.TaskitemData.ipEndPoint].Send(deleteObj);
                    }
                }
            }
        }

        public List<DSkin.Controls.DSkinTreeViewNode> nodeCheckedList;

        DS.FolderForm folderform;
        DS.CommandsForm commandsForm;

        /// <summary>
        /// 选择importfolder
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Import_Click(object sender, EventArgs e)
        {
            folderform = new DS.FolderForm();
            folderform.StartPosition = FormStartPosition.Manual;
            folderform.Location = new Point(this.Left+(this.Width-folderform.Width) / 2,this.Top+ (this.Height-folderform.Height)/2);
            folderform.ShowDialog();

            nodeCheckedList = folderform.nodeCheckedList;

            if (nodeCheckedList != null)
            {
                foreach (DSkin.Controls.DSkinTreeViewNode node in nodeCheckedList)
                {
                    if (Directory.Exists(node.Name))
                    {
                        //AddTaskItem(node.Name);
                        Common.TaskItemData taskItemData = new Common.TaskItemData(node.Name,"",Common.TaskItemState.idle);
                        AddTaskItem(taskItemData);
                    }
                }
            }
            
        }

        /// <summary>
        /// 选择命令
        /// </summary>
        /// <returns></returns>
        private List<string> getCheckedCommand() 
        {
            commandsForm = new DS.CommandsForm();
            commandsForm.StartPosition = FormStartPosition.Manual;
            commandsForm.Location = new Point(this.Left + (this.Width - commandsForm.Width) / 2, this.Top + (this.Height - commandsForm.Height) / 2);
            commandsForm.ShowDialog();

            return commandsForm.selectedCommands;
        }

        private void btADDTest_Click(object sender, EventArgs e)
        {
            tasklistdata = getCheckedCommand();
            string ra = DateTime.Now.ToString()+DateTime.Now.Millisecond.ToString();
            for(int i=0;i<20;i++)
            {
                string dir = i.ToString();
                Common.TaskItemData taskItemData = new Common.TaskItemData(ra + "  " + dir,"",Common.TaskItemState.idle);
                taskItemData.commands = tasklistdata;
                AddTaskItem(taskItemData);
            }
        }

        /// <summary>
        /// 服务器停止分配任务并向客户端发送停止消息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_stop_Click(object sender, EventArgs e)
        {
            if (bContinue)
            {
                foreach (DS.Controls.DSClientListItem dSClientListItem in dSkinListBoxClient.Items)
                {
                    //if (dSClientListItem.clientItemData.clientItemState == Common.ClientItemState.busy)
                    {
                        byte[] stateObj = SC.MessagePack.SerializeObject(SC.MessageType.Pause, Common.ClientItemState.idle);
                        socketServer.dicSocket[dSClientListItem.clientItemData.ipEndPoint].Send(stateObj);
                    }
                }
                this.btn_stop.Text = "Continue";
                Common.Log.Warn("手动停止任务");
            }
            else
            {
                foreach (DS.Controls.DSClientListItem dSClientListItem in dSkinListBoxClient.Items)
                {
                    //if (dSClientListItem.clientItemData.clientItemState == Common.ClientItemState.idle)
                    {
                        byte[] stateObj = SC.MessagePack.SerializeObject(SC.MessageType.Continue, Common.ClientItemState.busy);
                        try
                        {
                            socketServer.dicSocket[dSClientListItem.clientItemData.ipEndPoint].Send(stateObj);
                        }
                        catch(Exception ex)
                        {
                            Common.Log.Warn(ex.Message,ex);
                        }  
                    }
                }
                this.btn_stop.Text = "Pause";
                Common.Log.Warn("手动继续任务");
            }

            bContinue = !bContinue;
        }
    }
}